// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东（ShirDon）
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++

package main

import (
	"fmt"
	"math/rand"
)

// 定义单链表
type ListNode struct {
	Data int
	Next *ListNode
}

type Head struct {
	head *ListNode
}

// 初始化链表
func NewListNode(head *ListNode) Head {
	return Head{head: head}
}

// 返回随机节点的值
func (h *Head) GetRandom() int {
	scope, selectPoint, curr := 1, 0, h.head
	for curr != nil {
		if rand.Float64() < 1.0/float64(scope) {
			selectPoint = curr.Data
		}
		scope += 1
		curr = curr.Next
	}
	return selectPoint
}

func main() {
	nodeList := ListNode{6, nil}
	head := NewListNode(&nodeList)
	obj := NewListNode(head.head)
	ret := obj.GetRandom()
	fmt.Println(ret)
}
